/*
 * @Author: your name
 * @Date: 2022-04-22 14:55:27
 * @LastEditTime: 2022-04-26 10:59:08
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \mallAdmin\src\app\main\used-store\used-marketing-manage\second-coupon-details\second-coupon-details.component.ts
 */
import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { SecondCouponService } from '../services/second-coupon.service';

@Component({
  selector: 'app-second-coupon-details',
  templateUrl: './second-coupon-details.component.html',
  styleUrls: ['./second-coupon-details.component.scss']
})
export class SecondCouponDetailsComponent implements OnInit {
  
  routeParams: any = {};
  gridStyle = {
    width: '25%',
    textAlign: 'center'
  };

  // coupon details
  basicInfoData: any = {}; // 基本信息 & 适用商品
  useInfos: any = [
    { title: '最大发行数量', key: 'total', unitName: '个', tips: '优惠券总量' },
    { title: '已领取', key: 'numberReceived', percentage: '', percentageKeys: ['numberReceived', 'total'], tips: '已领取数量' },
    { title: '已使用', key: 'usedNumber', percentage: '', percentageKeys: ['numberReceived', 'usedNumber', 'numberReceived'], tips: '所有“状态 = 已使用”的数量' },
    { title: '用券总成交额', key: 'totalTurnover', unitName: '￥', tips: '所有“有效订单”中的用券总成交额' },
    { title: '优惠总金额', key: 'totalDiscountAmount', unitName: '￥', tips: '所有“状态 = 已使用”的优惠券的“实际抵扣”的合计' },
    { title: '费效比', key: 'costEffectiveness', percentage: '', percentageKeys: ['totalTurnover', 'totalDiscountAmount', 'totalTurnover'], tips: '用券总金额 / 用券成交总额' },
    { title: '用券笔单价', key: 'customerPrice', unitName: '￥', tips: '所有“有效订单”总额 / 有效订单数量' },
    { title: '购买商品数', key: 'paidGoodsNum', unitName: '个', tips: '所有“有效订单”中包含的商品总数' }
  ]; // 使用信息(注：百分比参考配件优惠券)
  userCouponsTableData: any = []; // 用户优惠券

  // 用户优惠券 Table
  userCouponTableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };

  // 用户优惠券状态
  userCouponsOptions: any = [
    { value: 1, label: '待使用' },
    { value: 2, label: '售后中' },
    { value: 3, label: '已过期' },
    { value: 4, label: '已使用' },
    { value: 5, label: '强制停止' }
  ];
  selectedUseCoupon: any = [];

  // 手动发券 Modal
  releaseVisible = false;
  releaseLoading = false;
  opreaItem: any = {};

  // 撤回用户用券 Modal
  isWithdrawVisible = false;
  withdrawItem: any = {};
  withdrawType: number = 0;
  withdrawLoading: boolean = false;
  withdrawParams: any = {
    remark: ''
  };

  // 适用商品查看
  isPreviewVisible: boolean = false;
  previewModalTitle: string = '查看可用商品';
  previewIds: any = [];

  // 成色
  conditionOptionsB: any = [];
  conditionOptionsC: any = [];

  constructor(
    private message: NzMessageService,
    private ActivatedRoute: ActivatedRoute,
    private commonService: CommonService,
    public permission: PermissionService,
    private services: SecondCouponService
  ) {
    ActivatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.initConditionDatas();
    this.loadDetails();
  }

  // 成色 query options
  async initConditionDatas() {
    this.conditionOptionsB = await this.commonService.getDictList('machine_condition_b');
    this.conditionOptionsC = await this.commonService.getDictList('machine_condition');
  }

  conditionFilter(arr: any[], str: string) {
    let tempArr = str.split(',').map((m: any) => +m);
    let tempStr: any = [];
    if (arr.length) {
      arr.forEach((item: any) => {
        if (tempArr.includes(item.id)) {
          tempStr.push(item.name);
        }
      })
    }
    return tempStr.join('、');
  }

  findUseInfo(key: string) {
    let obj: any = this.useInfos.find((ele: any) => ele.key === key);
    return obj?.sumNum ? obj?.sumNum : 0;
  }

  async loadDetails() {
    let params = {
      id: this.routeParams.id,
      couponUserRecordDTO: {
        statusStr: this.selectedUseCoupon.join(','),
        pageNum: this.userCouponTableParams.page,
        pageSize: this.userCouponTableParams.pageSize
      }
    }
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const res: any = await this.services.getCouponDetails(params);
    this.message.remove(messId);

    if (res.code === 0) {
      const { rechargeCouponInfo, useCouponInfo, couponUserRecordIPage } = res.data || {};
      this.basicInfoData = rechargeCouponInfo || {};

      // 用户优惠券 Table
      this.userCouponTableParams.tableData = couponUserRecordIPage?.records || [];
      this.userCouponTableParams.total = couponUserRecordIPage?.total || 0;
      
      // 使用信息
      this.useInfos.forEach((item: any) => {
        item.sumNum = useCouponInfo[item.key] || 0;
        if (item.hasOwnProperty('percentage')) {
          // 参考配件优惠券
          if (item.percentageKeys && item.percentageKeys.length === 3) {
            item.percentage = this.percentageCalc(this.findUseInfo(item.percentageKeys[0]) === 0 ? 0 : this.findUseInfo(item.percentageKeys[1]), this.findUseInfo(item.percentageKeys[2]));
          } else {
            item.percentage = this.percentageCalc(this.findUseInfo(item.percentageKeys[0]), this.findUseInfo(item.percentageKeys[1]));
          }
        }
      });
    } else {
      this.message.error(res.message);
    }
  }

  searchUseCoupon() {
    this.userCouponTableParams.page = 1;
    this.loadDetails();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.userCouponTableParams.page = index;
    this.loadDetails();
  }
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.userCouponTableParams.page = 1;
    this.userCouponTableParams.pageSize = sizeNum;
    this.loadDetails();
  }

  /**
   * 手动发放优惠券
   * ----------------------------------------------------------------
   */
  showCouponModal() {
    this.releaseVisible = true;
  }

  submitManual(val: any) {
    this.loadDetails();
  }

  /**
   * 撤回优惠券
   * ----------------------------------------------------------------
   */
  showWithdrawModal(type: number, item?: any) {
    this.withdrawParams.remark = '';
    this.withdrawType = type;
    if (item) {
      this.withdrawItem = item;
    }
    this.isWithdrawVisible = true;
  }

  async subWithdraw() {
    if (this.withdrawParams.remark === '') {
      this.message.warning('请先输入撤回原因');
      return
    }

    let params: any = {
      remark: this.withdrawParams.remark,
      type: 2,
      ids: []
    }
    let idArrs = this.userCouponTableParams.tableData.length ? this.userCouponTableParams.tableData.map((item: any) => item.id) : [];
    params.ids = this.withdrawType === 0 ? [...idArrs] : [this.withdrawItem.id];

    this.withdrawLoading = true;
    const res: any = await this.services.stopUserCoupon(params);
    this.withdrawLoading = false;

    if (res.code === 0) {
      this.message.success('操作成功');
      this.isWithdrawVisible = false;
      this.loadDetails();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 撤回优惠券
   * ----------------------------------------------------------------
   */
  showPreviewModal(arr: any[]) {
    this.previewIds = arr;
    this.isPreviewVisible = true;
  }

  // 使用信息百分比
  percentageCalc(num1: any, total: any) {
    let scaleNum: number = 0;
    scaleNum = isNaN((num1 || 0) / (total || 0)) ? 0 : (num1 || 0) / (total || 0);
    return (num1 === 0 || total === 0) ? 0 : (scaleNum * 100).toFixed(2);
  }

  // 优惠券信息状态filter
  couponStatusFilter(status: number) {
    let tempObj: any = this.userCouponsOptions.find((item: any) => item.value === status);
    return tempObj?.label || '-'
  }

  // arr size
  strToArray(str: string) {
    let arr: any[] = [];
    if (str && str !== '0') {
      arr = str.split(',');
    }
    return arr;
  }
}
